// Handle uploader
starter.directive('edUploader', ['$parse', '$timeout', '$ionicLoading','FileUploader', 'Page',
    function ($parse, $timeout, $ionicLoading, FileUploader, Page) {
    return {

        restrict: 'A',
        scope: {
            model : '=ngModel',
            dir: '@edUploadDir'
        },
        require: 'ngModel',

        template: function (elem, attrs) {
            var option = AppUtil.jsonfy(attrs.options);
            // 兼容老的方式
            option.multiple = option.multiple || (attrs.edMultiple == 'true');
            return '<div class="attachments margin-bottom-10" ng-if="' + option.multiple + '">'
                + '</div>'
                //+ '  <input type="file" class="margin-top-10" nv-file-select="" uploader="uploader" multiple/>'
                + '<div ng-style="uploadDivStyle"> '
                + '<img src="img/icon/shizi.png" height="20px" width="20px" style="position: relative;left: 32px;top:12px" />'
                + ' <span id="text" ng-style="textStyle">' + (option.text || '选择文件') + '</span>'
                //+ '<img id="progressImg" ng-show="showProgressImg" src="img/icon/3.gif" width="98%" height="80%">'
                //+ '<img id="imgSpan" ng-show="showImgSpan" style="padding-left:2px;width: 98%;height:98% " ng-src="{{testUrl}}">'
                + ' <input id="fileInput" ng-style="textSpanStyle" type="file" capture="camera" accept="' + (option.accept || '*') + '" nv-file-select="" uploader="uploader" ' + (option.multiple ? ' multiple' : '') + '>'
                + '</div>';
        },

        controller: ['$scope', '$element', '$rootScope','ApiEndpoint','localStore', function($scope, $element, $rootScope,ApiEndpoint,localStore){

            var userId = localStore.get("userId");
            var access_token = localStore.get("token");
            var user = {name : userId};
            $scope.author = user;
            $scope.nginxPath = $rootScope.nginxPath;

            var strPath = window.document.location.pathname;
            var contextPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);

            var uploader = $scope.uploader = new FileUploader({

                url: ApiEndpoint.uploadExAppUrl + "?access_token=" + access_token  + "&user_id=" + userId
            });

            // FILTERS
            uploader.filters.push({
                name: 'customFilter',
                fn: function (item /*{File|FileLikeObject}*/, options) {
                    return this.queue.length < 10;
                }
            });
        }],

        link: function (scope, elem, attrs, ngModelController) {

            var screenHeight = screen.width;

            scope.uploadDivStyle = {
                "width" : (screen.width - 10) / 4 + "px",
                "height" : "70px",
                "margin-top" : "-5px",
                "margin-left" : "-5px"
            }

            scope.showText = true;
            scope.textStyle = {
                "width" : (screen.width - 10) / 4 + "px",
                "height" : "40px",
                "position" : "relative",
                "top" : "36px",
                "left":  "-6px",
                "font-size" : '11px',
                "color" : "#9F9F9F"
            }
            scope.textSpanStyle = {
                "height" : "70px",
                "width" : (screen.width - 10) / 4 + "px",
                "position" : "relative",
                //"top" : "-30px",
                //"left" : "0"
                "top" : "-24px",
                "left" : "4px"
            }
            //width:150px;height:80px;top: 80px;left: -20%

            var option = AppUtil.jsonfy(attrs.options);
            // 兼容老的方式
            option.multiple = option.multiple || (attrs.edMultiple == 'true');
            // 单个文件上传或多文件上传
            scope.multiple = option.multiple;
            var uploadDir = scope.dir || '';
            var acceptType = option.accept || '*';

            // 上传前
            scope.uploader.onBeforeUploadItem = function (item) {
                var file = item.file;
                item.formData = [{name: file.name, size: file.size, type: file.type, author: scope.author, uploadDir: uploadDir}];
            };

            // 添加文件之后就开始上传
            scope.uploader.onAfterAddingFile = function(fileItem) {
                fileItem.upload();
            };

            scope.uploader.onWhenAddingFileFailed = function(item, filter, options) {
                if (filter.name == 'fileTypeFilter') {
                    Page.notice('上传文件类型不正确！');
                } else if (filter.name == 'maxSizeFilter') {
                    Page.notice('文件大小超过限制！');
                }
            };

            if (angular.isNumber(option.maxSize)) {
                scope.uploader.filters.push({
                    name: 'maxSizeFilter',
                    fn: function (item, options) {
                        return item.size <= option.maxSize * 1000;
                    }
                });
            }

            // FILTERS
            if (scope.multiple && angular.isNumber(option.maxLength)) {
                scope.uploader.filters.push({
                    name: 'maxLengthFilter',
                    fn: function (item , options) {
                        var files = ngModelController.$viewValue;
                        var filesLength = 0;
                        if(files instanceof Array){
                            filesLength = files.length;
                        }
                        return (filesLength + this.queue.length) < option.maxLength;
                    }
                });
            }

            scope.uploader.filters.push({
                name: 'fileTypeFilter',
                fn: function (item, options) {
                    var mime = item.type;
                    if ("application/msword" == mime) {
                    } else if ("application/vnd.openxmlformats-officedocument.wordprocessingml.document" == mime) {
                        mime = "application/msword";
                    } else if ("application/vnd.ms-excel" == mime) {
                        mime = "application/vnd.ms-excel";
                    } else if ("application/vnd.ms-excel application/x-excel" == mime) {
                        mime = "application/vnd.ms-excel";
                    } else if ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" == mime) {
                        mime = "application/vnd.ms-excel";
                    } else if ("application/vnd.ms-powerpoint" == mime) {
                    } else if ("application/vnd.openxmlformats-officedocument.presentationml.presentation" == mime) {
                        mime = "application/vnd.ms-powerpoint";
                    } else if ("application/vnd.ms-powerpoint" == mime) {
                        //mime = "pps";
                    } else if ("application/vnd.openxmlformats-officedocument.presentationml.slideshow" == mime) {
                        mime = "application/vnd.ms-powerpoint";
                    } else if ("application/pdf" == mime) {
                        //mime = "pdf";
                    } else if ("application/x-shockwave-flash" == mime) {
                        //mime = "swf";
                    } else if ("application/x-msdownload" == mime) {
                        //mime = "exe";
                    } else if ("application/octet-stream" == mime) {
                        var reg = new RegExp(".rar$");
                        if (item.name != null && reg.test(item.name)) {
                            mime = "rar";
                        } else {
                            mime = "exe";
                        }
                    } else if ("application/x-tar" == mime || "application/x-compressed" == mime
                        || "application/x-zip-compressed" == mime || "application/x-compress" == mime) {
                        mime = "rar";
                    } else if ("audio/wav" == mime) {
                        //mime = "wav";
                    } else if ("audio/x-ms-wma" == mime) {
                        //mime = "wma";
                    } else if ("video/x-ms-wmv" == mime) {
                        //mime = "wmv";
                    } else if ("audio/mpeg" == mime) {
                        //mime = "mp3";
                    } else if ("application/vnd.rn-realmedia" == mime) {
                        //mime = "rm";
                    } else if ("audio/mid" == mime) {
                        //mime = "mid";
                    } else if ("image/bmp" == mime) {
                        //mime = "bmp";
                    } else if ("image/gif" == mime) {
                        //mime = "gif";
                    } else if ("image/png" == mime) {
                        //mime = "png";
                    } else if ("image/tiff" == mime) {
                        //mime = "tif";
                    } else if ("image/jpeg" == mime) {
                        //mime = "jpg";
                    } else if ("text/plain" == mime) {
                        //mime = "txt";
                    } else if ("text/xml" == mime) {
                        //mime = "xml";
                    } else if ("text/html" == mime) {
                        //mime = "html";
                    } else if ("text/css" == mime) {
                        //mime = "css";
                    } else if ("text/javascript" == mime) {
                        //mime = "js";
                    } else if ("message/rfc822" == mime) {
                        //mime = "mht";
                    } else {
                        var index = item.name.lastIndexOf('.');
                        if (index > 0) {
                            mime = item.name.substring(index + 1);
                        } else {
                            mime = "unknown";
                        }
                    }
                    var accept = acceptType.trim() == '*';
                    if (!accept) {
                        $(acceptType.split(',')).each(function(i, type) {
                            type = type.trim();
                            if ((type.substring(type.length - 1) == '*' && mime.indexOf(type.substring(0, type.length - 1)) == 0) || type == mime) {
                                accept = true;
                                return false;
                            }
                        });
                    }
                    return accept;
                }
            });

            scope.uploader.onProgressItem  = function(item, progress) {

                scope.showImgSpan = false;
                scope.showText = false;

                $ionicLoading.show({
                    content: 'Loading',
                    animation: 'fade-in',
                    showBackdrop: true,
                    maxWidth: 200,
                    showDelay: 0
                });

                scope.showProgressImg = true;


                //$("#text").css("display","none");
                //$("#progressImg").css("display","block");
                //$("#imgSpan").css("display","none");
            }

            // 上传成功
            scope.uploader.onSuccessItem = function(fileItem, response, status, headers) {
                //$timeout(function () {
                //    $ionicLoading.hide();
                //}, 2000);
                $ionicLoading.hide();
                $(elem).find("input").val("");

                var file = response.data;
                file.author = scope.author.name;

                if (scope.multiple) {// 多选
                    var files = ngModelController.$viewValue || [];
                    files.push(file);
                    // call $parsers pipeline then update $modelValue
                    ngModelController.$setViewValue(files);
                } else {// 单选
                    ngModelController.$setViewValue(file);
                }
                // update the local view
                ngModelController.$render();

                scope.showImgSpan = true;
                scope.showText = false;
                scope.showProgressImg = false


                //scope.textSpanStyle = {
                //    "height" : scope.textSpanStyle.height,
                //    "width" : scope.textSpanStyle.width,
                //    "position" : "relative",
                //    "top" : "-65%",
                //    "left" : "0"
                //}
                //$("#text").css("display","none");
                //$("#progressImg").css("display","none");
                //$("#imgSpan").css("display","block");
                //scope.testUrl = scope.nginxPath + file.path;
                //$(elem).after('<div class="col col-25" align="center" style="height: 70px;margin-left: 5px;border:1px dashed #E5E5E5" onclick="showBig(' + '\'' + file.path + '\')">' +
                //'<img src="' + scope.testUrl + '" style="height: 70px;margin-top: -6px;"/>'
                //+'</div>')
            };

            scope.uploader.onCompleteAll = function() {
                scope.uploader.clearQueue();
            };

            // 删除文件
            scope.delete = function(file) {
                if (scope.multiple) {// 多选
                    var files = [];
                    for (var i = 0, len = ngModelController.$viewValue.length; i < len; i++) {
                        var f = ngModelController.$viewValue[i];
                        if (file.url != f.url) {
                            files.push(f);
                        }
                    }
                    // call $parsers pipeline then update $modelValue
                    ngModelController.$setViewValue(files);
                } else {
                    ngModelController.$setViewValue(null);
                }
                // update the local view
                ngModelController.$render();
            }

        }

    };

}]);
